import Vue from 'vue'
import Vuex from 'vuex';
// import fly from '@/utils/request.js';
Vue.use(Vuex)
const store = new Vuex.Store({
	state: {
		token: "",
		tokenExpired: "",
		uid: "",
		username: "",
		userInfo: {},
		updateCart:false
	},
	mutations: {
		updateCartHandler(state){
			state.updateCart = !state.updateCart
		},
		//通用的提交数据的方法
		setData(state, param) {
			for (let i in param) {
				state[i] = param[i];
			}
		},
		logout(state) {
			for (let i in state) {
				if (i == 'userInfo') {
					state[i] = {}
				} else {
					state[i] = '';
				}
			}
		}
	},
	actions: {
		//actions  管不了存储数据的事   他只管分发
		getuserInfo({
			commit,
			state,
			dispatch
		}) {
			//去服务器请求最新的用户信息
			let token = uni.getStorageSync('token');
			fly.post('/user', {
				module: "getuserInfo",
				token
			}).then(res => {
				if (res.code == 0) {
					commit('setData', {
						username: res.userInfo.username,
						uid: res.userInfo._id,
						userInfo: res.userInfo
					});
					
				}

			}).catch(err => {
				console.log(err)
			});

		}
	


	}
})

export default store
